package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.mapper.EmployeeMapper;
import cn.wolfcode.wms.mapper.PermissionMapper;
import cn.wolfcode.wms.page.PageResult;
import cn.wolfcode.wms.query.EmployeeQueryObject;
import cn.wolfcode.wms.service.IEmployeeService;
import cn.wolfcode.wms.util.MD5;
import cn.wolfcode.wms.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    public PageResult query(EmployeeQueryObject qo) {
        int rows = employeeMapper.queryForCount(qo);
        if (rows == 0) {
            return PageResult.empty(qo.getPageSize());
        }
        List<?> result = employeeMapper.queryForList(qo);
        return new PageResult(result, rows, qo.getCurrentPage(), qo.getPageSize());
    }

    public Employee getById(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    public void update(Employee emp,Long[] roleIds) {
        employeeMapper.updateByPrimaryKey(emp);
        employeeMapper.deleteRelationByEmployeeId(emp.getId());
        if(roleIds != null){
            for (Long id : roleIds) {
                employeeMapper.saveRelationByEmployeeId(emp.getId(),id);
            }
        }
    }

    public void save(Employee emp,Long[] roleIds) {
        String password = emp.getPassword();
        String encodePassword = MD5.encode(password);
        emp.setPassword(encodePassword);
        employeeMapper.insert(emp);
        if(roleIds != null){
            for (Long id : roleIds) {
                employeeMapper.saveRelationByEmployeeId(emp.getId(),id);
            }
        }
    }

    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
        employeeMapper.deleteRelationByEmployeeId(id);
    }

    public void login(String username, String password) {
        String encodePassword = MD5.encode(password);
        Employee employee = employeeMapper.selectByInfo(username,encodePassword);
        if (employee == null) {
            throw new RuntimeException("账号和密码不匹配");
        }
        UserContext.setCurrentUser(employee);
        if(!employee.isAdmin()){
            Set<String> expressions = permissionMapper.selectByEmployeeId(employee.getId());
            UserContext.setExpression(expressions);
        }
    }

    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
    }
}
